package com.wxw.springcloud.feign.controller;

import com.wxw.springcloud.feign.config.DistributedLockHandler;
import com.wxw.springcloud.feign.dao.OrderMapper;
import com.wxw.springcloud.feign.po.Lock;
import com.wxw.springcloud.feign.po.Order;
import com.wxw.springcloud.feign.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wxw
 * @data 2021/11/14 20 :40
 * @description
 */
@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    DistributedLockHandler distributedLockHandler;
    /**
     * 注意使用Global会导致srping原生事务注解失效 若要使用需从新配置！！！(已配置)
     * @param id
     */
    @PostMapping("add")
    @GlobalTransactional
    public  void  addOrder(@RequestParam("id") Integer id){
        Order order = new Order();
        order.setOrderId("123456");
        order.setTradeId(id);
        log.info("开始添加订单");
        orderMapper.addOrder(order);
        Lock lock = new Lock(id.toString(),id.toString());
        //开启分布式锁
        if(distributedLockHandler.tryLock(lock)){
        log.info("添加订单完成,开始减少库存");
        orderService.InventoryReduction(id);
            //distributedLockHandler.releaseLock(lock);
        }
        // throw new RuntimeException();
    }
}
